package com.example.qixinshangwutong.view.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.qixinshangwutong.BaseApplication;
import com.example.qixinshangwutong.R;

import com.example.qixinshangwutong.model.brand.MyAdapter;
import com.example.qixinshangwutong.model.brand.SortAdapter;
import com.example.qixinshangwutong.model.brand.SortModel;
import com.example.qixinshangwutong.model.brand.SortRequest;
import com.example.qixinshangwutong.model.brand.SortValues;
import com.example.qixinshangwutong.view.activity.CompanyActivity;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class BrandFragment extends Fragment {
    private LinearLayout diqu;
    private ImageView diquIcon;
    private LinearLayout hangye;
    private ImageView hangyeIcon;
    private LinearLayout paixu;
    private ImageView paixuIcon;
    private RecyclerView recyclerView;
    private MyAdapter<String> adapter, adapter1, adapter2;
    private PopupWindow popupWindow;
    private SwipeRecyclerView swipeRecyclerView;
    private SmartRefreshLayout refreshLayout;
    private List<SortModel> list;
    private SortAdapter sortAdapter;
    private int page = 1;
    private String sort;
    private int listSize;
    private ImageView noDataImage;
    private String currentDiQu,currentHangYe,currentSort;
    private List<String> popList,popList1,popList2;
    private Map<String ,Integer> popMap,popMap1,popMap2;
    private TextView diquText,hangyeText,sortText;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_brand, container, false);
        initView(root);
        getList();
        getMap();
        initView();

        return root;
    }

    private void initView(View root) {
        diqu = root.findViewById(R.id.brand_select_diqu);
        diquIcon = root.findViewById(R.id.brand_select_diqu_icon);
        diquText=root.findViewById(R.id.brand_select_diqu_tittle);
        hangye = root.findViewById(R.id.brand_select_hangye);
        hangyeIcon = root.findViewById(R.id.hangye_icon);
        hangyeText=root.findViewById(R.id.brand_select_hangye_tittle);
        paixu = root.findViewById(R.id.brand_select_paixu);
        paixuIcon = root.findViewById(R.id.brand_paixu_icon);
        sortText=root.findViewById(R.id.brand_select_paixu_tittle);
        diqu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                diquIcon.setImageResource(R.mipmap.shaixuan_sql);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setAdapter(adapter);
                popupWindow.showAsDropDown(diqu);
            }
        });
        hangye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hangyeIcon.setImageResource(R.mipmap.shaixuan_sql);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setAdapter(adapter1);
                popupWindow.showAsDropDown(hangye);
            }
        });
        paixu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                paixuIcon.setImageResource(R.mipmap.shaixuan_sql);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setAdapter(adapter2);
                popupWindow.showAsDropDown(paixu);
            }
        });
        swipeRecyclerView = root.findViewById(R.id.fragment_recycle);
        refreshLayout = root.findViewById(R.id.smart_refresh);
        swipeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        list = new ArrayList<>();
        sortAdapter=new SortAdapter(getActivity());
        sortData(sort,getDq(),getHangYe(),1);
        sortAdapter.setDataList(list);
        swipeRecyclerView.setAdapter(sortAdapter);
        smartRefresh();
        noDataImage=root.findViewById(R.id.no_data_icon);

    }

    private void initView(){
        View contentView=getLayoutInflater().inflate(R.layout.pop_list_item,null);
        popupWindow=new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,false);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setFocusable(true);
        //popupWindow.setAnimationStyle(R.style.PopupAnimation);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        recyclerView=contentView.findViewById(R.id.pop_list);
        contentView.findViewById(R.id.pop_list_bottom).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        adapter=new MyAdapter<>(R.layout.pop_listview_item,popList);
        adapter.setOnCallBackData(new MyAdapter.onCallBackData<String>() {
            @Override
            public void convertView(BaseViewHolder holder, String item) {
                ((TextView)holder.getView(R.id.listview_popwind_tv)).setText(item);
                if (diquText.getText().toString().trim().equals(item)){
                    ((TextView) holder.getView(R.id.listview_popwind_tv)).setTextColor(Color.parseColor("#00d8a0"));
                }else{
                    ((TextView) holder.getView(R.id.listview_popwind_tv)).setTextColor(Color.parseColor("#333333"));
            }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                popupWindow.dismiss();
                currentDiQu=popList.get(position);
                diquText.setText(currentDiQu);
                if (currentDiQu.equals(popList.get(position))){
                    list.clear();
                    sortData(sort,getDq(),getHangYe(),0);
                }
            }
        });

        adapter1=new MyAdapter<>(R.layout.pop_listview_item,popList1);
        adapter1.setOnCallBackData(new MyAdapter.onCallBackData<String>() {
            @Override
            public void convertView(BaseViewHolder holder, String item) {
                ((TextView)holder.getView(R.id.listview_popwind_tv)).setText(item);
                if (hangyeText.getText().toString().trim().equals(item)){
                    ((TextView) holder.getView(R.id.listview_popwind_tv)).setTextColor(Color.parseColor("#00d8a0"));
                }else{
                    ((TextView) holder.getView(R.id.listview_popwind_tv)).setTextColor(Color.parseColor("#333333"));
                }
            }
        });
        adapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                popupWindow.dismiss();
                currentHangYe=popList1.get(position);
                hangyeText.setText(currentHangYe);
                if (currentHangYe.equals(popList1.get(position))){
                    list.clear();
                    sortData(sort,getDq(),getHangYe(),0);
                }
            }
        });

        adapter2=new MyAdapter<>(R.layout.pop_listview_item,popList2);
        adapter2.setOnCallBackData(new MyAdapter.onCallBackData<String>() {
            @Override
            public void convertView(BaseViewHolder holder, String item) {
                ((TextView)holder.getView(R.id.listview_popwind_tv)).setText(item);
                if (sortText.getText().toString().trim().equals(item)){
                    ((TextView) holder.getView(R.id.listview_popwind_tv)).setTextColor(Color.parseColor("#00d8a0"));
                }else{
                    ((TextView) holder.getView(R.id.listview_popwind_tv)).setTextColor(Color.parseColor("#333333"));
                }
            }
        });
        adapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                popupWindow.dismiss();
                currentSort=popList2.get(position);
                sortText.setText(currentSort);
                if (position==0){
                    list.clear();
                    sortData(sort,getDq(),getHangYe(),0);
                }
                if (position==1){
                    list.clear();
                    sort="-ut";
                    sortData(sort,getDq(),getHangYe(),0);
                }
               if(position==2){
                    list.clear();
                    sort="ut";
                    sortData(sort,getDq(),getHangYe(),0);
                }
                sort="";

            }
        });

    }

    /*
    http://api.qxswt.com/index/brand?sort&ssdq_code=0&hylb_code=0&page=1
     */
    private void sortData(String sort, int ssdp_code, int hylb_code, int page) {
        Call<SortRequest<SortValues>> call = BaseApplication.api.getSortData(sort, ssdp_code, hylb_code, page);
        call.enqueue(new Callback<SortRequest<SortValues>>() {
            @Override
            public void onResponse(Call<SortRequest<SortValues>> call, Response<SortRequest<SortValues>> response) {
                for (int i = 0; i < response.body().getValues().getModel().size(); i++) {
                    Log.d("品牌id", response.body().getValues().getModel().get(i).getMapping_id());
                    SortModel model=new SortModel();
                    model.setSortIcon(response.body().getValues().getModel().get(i).getUrl());
                    model.setSortPinpai(response.body().getValues().getModel().get(i).getPinpai());
                    model.setSortName(response.body().getValues().getModel().get(i).getCompany_name());
                    model.setSortId(response.body().getValues().getModel().get(i).getMapping_id());
                    list.add(model);

                }
                listSize=response.body().getValues().getTotalCount();
                sortAdapter.notifyDataSetChanged();
                if (list.isEmpty()){
                    noDataImage.setImageResource(R.mipmap.zanwushuju);
                }else{
                    noDataImage.setImageResource(0);
                }
                sortAdapter.setListener(new SortAdapter.onItemViewClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent=new Intent(getActivity(), CompanyActivity.class);
                        intent.putExtra("url","http://m.qxswt.com/company/"+list.get(position).getSortId());
                        intent.putExtra("name",list.get(position).getSortName());
                        intent.putExtra("murl",list.get(position).getSortIcon());
                        startActivity(intent);
                    }
                });

            }

            @Override
            public void onFailure(Call<SortRequest<SortValues>> call, Throwable t) {

            }

        });
    }
    private void smartRefresh(){
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(100,true,false);
                if (listSize>=10){
                    page++;
                    sortData(sort,getDq(),getHangYe(),page);
                }else {
                    refreshLayout.finishRefresh(50,true,true);
                }

            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(50,true,false);

            }
        });
    }
    private int getDq(){
        if (currentDiQu==null){
            return 0;
        }else{
            return popMap.get(currentDiQu);
        }

    }
    private int getHangYe(){
        return currentHangYe==null?0:popMap1.get(currentHangYe);
    }
    private void getList(){
        popList = new ArrayList<>();
        popList.add("全部地区");
        popList.add("安徽");
        popList.add("北京");
        popList.add("重庆");
        popList.add("福建");
        popList.add("广东");
        popList.add("甘肃");
        popList.add("广西");
        popList.add("贵州");
        popList.add("海南");
        popList.add("河北");
        popList.add("河南");
        popList.add("黑龙江");
        popList.add("湖北");
        popList.add("湖南");
        popList.add("吉林");
        popList.add("江苏");
        popList.add("江西");
        popList.add("辽宁");
        popList.add("内蒙古");
        popList.add("宁夏");
        popList.add("青海");
        popList.add("陕西");
        popList.add("四川");
        popList.add("山东");
        popList.add("上海");
        popList.add("山西");
        popList.add("天津");
        popList.add("新疆");
        popList.add("西藏");
        popList.add("云南");
        popList.add("浙江");
        popList.add("其他");

        popList1 = new ArrayList<>();
        popList1.add("全部行业");
        popList1.add("采矿业");
        popList1.add("制造业");
        popList1.add("电力、热力、燃气、及水生产和供应业");
        popList1.add("建筑业");
        popList1.add("批发和零售业");
        popList1.add("交通运输、仓储和邮政业");
        popList1.add("住宿和餐饮业");
        popList1.add("信息传输、软件和信息技术服务业");
        popList1.add("金融业");
        popList1.add("房地产业");
        popList1.add("租赁和商务服务业");
        popList1.add("科学研究和技术服务业");
        popList1.add("水利，环境和公共设施管理业");
        popList1.add("居民服务、修理和其他服务业");
        popList1.add("教育");
        popList1.add("卫生和社会工作");
        popList1.add("文化、体育和娱乐业");
        popList1.add("公共管理、社会保障和社会组织");
        popList1.add("国际组织");
        popList1.add("其他");

        popList2 = new ArrayList<>();
        popList2.add("默认排序");
        popList2.add("按时间正序");
        popList2.add("按时间倒序");
    }

    private void getMap(){
        popMap = new HashMap<>();
        popMap.put("全部地区",0);
        popMap.put("安徽",1);
        popMap.put("北京",2);
        popMap.put("重庆",4);
        popMap.put("福建",5);
        popMap.put("广东",6);
        popMap.put("甘肃",7);
        popMap.put("广西",8);
        popMap.put("贵州",9);
        popMap.put("海南",10);
        popMap.put("河北",11);
        popMap.put("河南",12);
        popMap.put("黑龙江",13);
        popMap.put("湖北",14);
        popMap.put("湖南",15);
        popMap.put("吉林",16);
        popMap.put("江苏",17);
        popMap.put("江西",18);
        popMap.put("辽宁",19);
        popMap.put("内蒙古",20);
        popMap.put("宁夏",21);
        popMap.put("青海",22);
        popMap.put("陕西",23);
        popMap.put("四川",24);
        popMap.put("山东",25);
        popMap.put("上海",26);
        popMap.put("山西",27);
        popMap.put("天津",28);
        popMap.put("新疆",29);
        popMap.put("西藏",30);
        popMap.put("云南",31);
        popMap.put("浙江",32);
        popMap.put("其他",33);

        popMap1 = new HashMap<>();
        popMap1.put("全部行业",0);
        popMap1.put("采矿业",1);
        popMap1.put("制造业",9);
        popMap1.put("电力、热力、燃气、及水生产和供应业",4);
        popMap1.put("建筑业",45);
        popMap1.put("批发和零售业",50);
        popMap1.put("交通运输、仓储和邮政业",53);
        popMap1.put("住宿和餐饮业",62);
        popMap1.put("信息传输、软件和信息技术服务业",65);
        popMap1.put("金融业",69);
        popMap1.put("房地产业",74);
        popMap1.put("租赁和商务服务业",76);
        popMap1.put("科学研究和技术服务业",79);
        popMap1.put("水利，环境和公共设施管理业",83);
        popMap1.put("居民服务、修理和其他服务业",87);
        popMap1.put("教育",91);
        popMap1.put("卫生和社会工作",93);
        popMap1.put("文化、体育和娱乐业",96);
        popMap1.put("公共管理、社会保障和社会组织",102);
        popMap1.put("国际组织",109);
        popMap1.put("其他",998);

        popMap2 = new HashMap<>();
        popMap2.put("默认排序",0);
        popMap2.put("按时间正序",1);
        popMap2.put("按时间倒序",2);

    }

}